package com.tuling.instance;

import java.io.*;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

/**
 * Created by chenhs on 2018/7/31.
 *
 * 对象创建方式：
 * 1、使用new关键字创建对象
 * 2、使用Class类的newInstance方法（反射机制）
 * 3、使用Constructor类的newInstance方法（反射机制）
 * 4、使用Clone方法创建对象
 * 5、使用（反）序列化机制创建对象
 *
 */
public class Student implements Cloneable, Serializable {

    private Integer id;

    public Student(){}

    public Student(Integer id) {
        this.id = id;
    }

    @Override
    protected Object clone() throws CloneNotSupportedException {
        return super.clone();
    }

    @Override
    public String toString() {
        return "Student{" +
                "id=" + id +
                '}';
    }

    public static void main(String[] args) throws Exception {

        System.out.println("使用new关键字创建对象：");
        Student stu1 = new Student();
        System.out.println("\n---------------------------\n");

/*        //对应类必须具有无参构造方法，且只有这一种创建方式
        System.out.println("使用Class类的newInstance方法创建对象：");
        Student stu2 = (Student) Class.forName("com.tuling.instance.Student").newInstance();
        System.out.println(stu2);
        System.out.println("\n---------------------------\n");*/


        System.out.println("使用Constructor类的newInstance方法创建对象：");
        Constructor<Student> constructor = Student.class.getConstructor(Integer.class);
        Student stu3 = constructor.newInstance(123);// 调用有参构造方法
        System.out.println(stu3);
        System.out.println("\n---------------------------\n");

        System.out.println("使用Clone方法创建对象：");
        Student stu4 = (Student) stu3.clone();
        System.out.println(stu4);
        System.out.println("\n---------------------------\n");

        System.out.println("使用(反)序列化机制创建对象：");
        //写对象
        ObjectOutputStream outputStream = new ObjectOutputStream(new FileOutputStream("student.bin"));
        outputStream.writeObject(stu3);
        outputStream.close();

        //读对象
        ObjectInputStream inputStream = new ObjectInputStream(new FileInputStream("student.bin"));
        Student stu5 = (Student) inputStream.readObject();
        inputStream.close();
        System.out.println(stu5);

    }
}
